
import React from 'react';
import cass from 'classnames';
import s from './index.module.less';
import config from '../../config';

const { baseUrl } = config;

export function StaticAvatar ({ headimage, username, noOrigin, borderColor, color, onError }) {
    
    const url = noOrigin ? headimage : `${baseUrl}/file/${headimage}`;
    return (
        <div className={cass('nodrag', s.avatar)}>
            {headimage ? <img src={url} alt="headimage" onError={onError}/> : (
                <div className={cass(borderColor || 'mainBorderColor', color, s.inner)}>
                    {username &&  typeof username === 'string' ?  username.slice(-2) : username || '未知'}  
                </div>
            )}
        </div>
    )  
}
export default class Avatar extends React.Component {

    constructor(props) {
        super(props);
        this.state={
            headimage: props.headimage
        }
    }

    componentWillReceiveProps(nextProps){
        if(this.props.headimage !== nextProps.headimage) {
            this.setState({ headimage: nextProps.headimage })
        }
    }

    onError = (e) => {
        this.setState({ headimage: undefined });
    }

    render(){
        return <StaticAvatar {...{...this.props, headimage: this.state.headimage}} onError={this.onError}/>
    }  
}

